import java.sql.*;
import java.util.ArrayList;

public class JDBCTest {

    // JDBC:Java操作数据库
    // SELECT id,name,age,gender FROM student;
    // ArrayList<Student> list;
    public static void main(String[] args) {
        try {
            // 1、加载驱动Class.forName("");
            Class.forName("com.mysql.jdbc.Driver");
            // 2、获得连接对象Connection
            Connection connection = DriverManager.getConnection("jdbc:mysql://localhost:3306/company?useUnicode=true&characterEncoding=UTF-8", "root", "1234");
            // 3、写sql语句
            String sql = "SELECT id,name,age,gender FROM student";
            // 4、创建Statement: 理解成一艘船，运送sql语句到服务器，返回结果给客户端
            Statement statement = connection.createStatement();
            // 5、执行sql语句
            //        (1) 更新类（更改了表里面数据）：delete/update/insert     executeUpdate()
            // 返回值：int，表示你影响的行数
            //        (2)查询（没有改变表里面数据）:  select                              executeQuery()
            ResultSet resultSet = statement.executeQuery(sql);
            ArrayList<Student> list = new ArrayList<>();
            // 返回值：结果集ResultSet
            // next() 判断下一行有没有，有返回true，没有返回false
            while (resultSet.next()) {
                // 每遍历一次封装一个Student对象
                int id = resultSet.getInt("id");
                String name = resultSet.getString("name");
                int age = resultSet.getInt("age");
                String gender = resultSet.getString("gender");

                Student student = new Student();
                student.setId(id);
                student.setName(name);
                student.setAge(age);
                student.setGender(gender);

                list.add(student);
            }

            for (Student student : list) {
                System.out.println(student);
            }

        } catch (ClassNotFoundException e) {
            e.printStackTrace();
        } catch (SQLException throwables) {
            throwables.printStackTrace();
        }

        // 6、关闭连接
    }

}
